package com.ifengchao.util.sina;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import sun.net.ftp.FtpClient;

public class FtpUtil {
	
	private static final Logger logger = Logger.getLogger( FtpUtil.class);
	
	
	
	/**
	 * 连接FTP服务器
	 * @param ip
	 * @param userName
	 * @param passWord
	 * @param path
	 * @return
	 */
//	public static  boolean connectServer(String ip,String userName,String passWord,String path){
//		
//		FtpClient ftpClient = null;  
//		try{
//			
//			ftpClient = new FtpClient();
//			ftpClient.openServer(ip);
//			ftpClient.login(userName, passWord);
//			
//			if(path.length() !=0){
//				ftpClient.cd(path);
//			}
//			ftpClient.binary();
//			System.out.println("已登录到\"" + ftpClient.pwd() + "\"目录");  
//			return true;
//		}catch(IOException  e){
//			logger.error("连接FTP报错");
//			e.printStackTrace();
//			return false;
//		}
//		
//	}
	
	/**
	 * 下载文件
	 * @param isConnect
	 * @param FileName
	 */
	public static boolean downLoad(String FileName,String ip,String userName,String passWord,String path,String upload){
		boolean isSuccess = false;
		FTPClient ftp = new FTPClient();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		try{
			int reply;
			ftp.connect(ip, 21);
			ftp.setControlEncoding("GB2312");
			ftp.login(userName, passWord);
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
			reply = ftp.getReplyCode();
			if(!FTPReply.isPositiveCompletion(reply)){
				ftp.disconnect();
				return isSuccess;
			}
			logger.info("登录成功！");
			ftp.changeWorkingDirectory(path+"/"+df.format(new Date()));
			FTPFile[] fs = ftp.listFiles();
			for(int i=0;i<fs.length;i++){
				FTPFile ff = fs[i];
				if(ff.getName().equals(FileName)){
					File file = new File(upload+FileName);
				//	File fileExists = new File(File.separator+"upload"+File.separator+"Excel"+File.separator);
					File fileExists = new File(upload);
					if(!fileExists.exists() && !fileExists.isDirectory()){
						logger.info("文件目录不存在");
						fileExists.mkdirs();
					}
					FileOutputStream fos = new FileOutputStream(file);
					String filename = path+"/"+df.format(new Date())+"/"+ff.getName();
					ftp.retrieveFile(new String(filename.getBytes("GB2312"),"ISO-8859-1"), fos);
					isSuccess = true;
				}
			}
			logger.info("downLoad success");
		}catch(IOException e){
			e.printStackTrace();
			
		}
    return isSuccess;
	}
	
	
	public static List<String[]> parseExcelFile(String fileName,int skipRow,int cols){
		List<String[]> data=new ArrayList<String[]>();
		FileInputStream input=null;
		try {
			if(fileName.toLowerCase().endsWith(".xls")){//2003
				input=new FileInputStream(new File(fileName));
				POIFSFileSystem fs=new POIFSFileSystem(input);  
			    HSSFWorkbook wb=new HSSFWorkbook(fs);  
			    HSSFSheet sheet=wb.getSheetAt(0);
			    int rowNum = sheet.getLastRowNum(); // 得到总行数  
			    HSSFRow row = sheet.getRow(0);
			    HSSFCell cell=null;
			    //String productType=null,loanTitle=null,loanUse=null,thirdId=null,realName=null,sex=null,cardid=null,mobile=null,education=null,source=null;
			    //double contractAmount=0,loanAmount=0,loanTime=0,loanInterest=0,monthlyComplexFeeRate=0;
			    //boolean isUrgent=false;
			    for (int i = skipRow; i <=rowNum; i++) {//跳过前两行
			    	row = sheet.getRow(i);
			    	String[] rowData=new String[cols];
	            	for(int j=0;j<cols;j++){
	            		cell=row.getCell(j);
	            		if(cell==null)
	            			continue;
	            		int cellType=cell.getCellType();
	            		if(cellType==HSSFCell.CELL_TYPE_NUMERIC){
	            			if(String.valueOf(cell.getNumericCellValue()).indexOf("E") != -1){
	            				rowData[j]=String.valueOf(new DecimalFormat("#").format(cell.getNumericCellValue()));
	            			}else{
	            				rowData[j]=String.valueOf(cell.getNumericCellValue());
	            			}
	            			
	            		}else if(cellType==HSSFCell.CELL_TYPE_STRING){
	            			rowData[j]=cell.getStringCellValue();
	            		}
	            		
	            	}
	            	data.add(rowData);
			    }
			}else if(fileName.toLowerCase().endsWith(".xlsx")){//2007
				input=new FileInputStream(new File(fileName));
				XSSFWorkbook wb=new XSSFWorkbook(input);
				XSSFSheet sheet=wb.getSheetAt(0);
				int rowNum = sheet.getLastRowNum(); // 得到总行数
				XSSFRow row=sheet.getRow(0);
				XSSFCell cell=null;
	            for (int i = skipRow; i <= rowNum; i++) {
	            	row = sheet.getRow(i);
	            	String[] rowData=new String[cols];
	            	for(int j=0;j<cols;j++){
	            		cell=row.getCell(j);
	            		if(cell==null)
	            			continue;
	            		int cellType=cell.getCellType();
		            	if(cellType==XSSFCell.CELL_TYPE_NUMERIC){
		            		if(String.valueOf(cell.getNumericCellValue()).indexOf("E") != -1){
	            				rowData[j]=String.valueOf(new DecimalFormat("#").format(cell.getNumericCellValue()));
	            			}else{
	            				rowData[j]=String.valueOf(cell.getNumericCellValue());
	            			}
		            	}else if(cellType==XSSFCell.CELL_TYPE_STRING){
		            		rowData[j]=cell.getStringCellValue();
		            	}
	            		
	            	}
	            	data.add(rowData);
	            }
			}
		} catch (Exception e) {
			logger.error("解析excel异常", e);
		}
		return data;
	}
	
	/**
	 * 上传文件
	 * @param ip
	 * @param port
	 * @param username
	 * @param password
	 * @param path
	 * @param filename
	 * @param input
	 * @return
	 */
	public static void upload(String ip,int port,String username, String password, String path, String filename,String upload){
		FTPClient ftpClient = new FTPClient(); 
		FileInputStream fis = null;
        try{
        	ftpClient.connect(ip, port);
        	ftpClient.login(username, password);
        	int reply =  ftpClient.getReplyCode();
        	 if(!FTPReply.isPositiveCompletion(reply)){
        		 ftpClient.disconnect();
 			}
        	SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        	ftpClient.changeWorkingDirectory(path); 
            ftpClient.setBufferSize(1024); 
            ftpClient.setControlEncoding("GBK" ); 
            
            File file = new File(upload+filename);
            fis = new FileInputStream(file);
            
            
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 
            ftpClient.storeFile(new String(filename.getBytes("GB2312"),"ISO-8859-1") , fis); 
            
        }catch(IOException e){
        	e.printStackTrace(); 
        	
        }finally{
        	try{
        			fis.close();
        		   ftpClient.disconnect(); 
        	}catch (Exception ex) {
                ex.printStackTrace(); 
            } 
        }
	}
	
	/**
	 * 删除
	 * @param FileName
	 * @return
	 */
	public static void delete(String FileName,String upload){
		File file = new File(upload+FileName);
		if(!file.exists()){
			return ;
		}else{
			if(file.isFile()){
				file.getAbsoluteFile().delete();
			}
		}
 		return ;
	}

	/**
	 * 判断文件是否存在
	 * @param exitFileName
	 * @param ip
	 * @param userName
	 * @param passWord
	 * @param path
	 * @return
	 */
	public static boolean fileIsExit(String exitFileName, String ip, String userName,
			String passWord, String path) {
		boolean isExit = false;
		FTPClient ftpClient = new FTPClient();
		try{
			ftpClient.connect(ip, 21);
			ftpClient.login(userName, passWord);
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
			path = path+"/"+df.format(new Date());
			ftpClient.changeWorkingDirectory(path);
			
			FTPFile[] fs = ftpClient.listFiles();
			for(int i=0;i<fs.length;i++){
				FTPFile ff = fs[i];
				if(ff.getName().equals(exitFileName)){
					isExit = true;
				}
			}
			
		}catch(Exception e){
			logger.error("查询文件是否存在"+e.getMessage());
		}
		return isExit;
	}


}
